# -*- coding: utf-8 -*-
import requests
from lxml import etree
import os

BASE_DIR = os.path.dirname(os.path.realpath(__file__))


class Spider:
    def send(self, asin: str):
        if asin:
            url = f"https://www.amazon.com/gp/product/{asin}/"
            headers = {
                "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
                "accept-encoding": "gzip, deflate, br",
                "accept-language": "zh-CN,zh;q=0.9",
                "cache-control": "no-cache",
                "service-worker-navigation-preload": "true",
                "upgrade-insecure-requests": "1",
                "user-agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36",
            }
            response = requests.get(url, headers=headers)
            if response.status_code == 200:
                file_path = os.path.join(BASE_DIR, "cache", "{}.html".format(asin))
                if not os.path.exists(file_path):
                    with open(file_path, 'wt', encoding='utf-8') as f:
                        f.write(response.text)
                    result = self.parse(file_path)
                    return result
                else:
                    result = self.parse(file_path)
                    return result
            else:
                return -1
        else:
            return -1

    def parse(self, file_path):
        check = lambda x: x[0] if x else ""
        if os.path.exists(file_path):
            with open(file_path, 'rt', encoding='utf-8') as f:
                content = f.read()
            html = etree.HTML(content)
            title = check(html.xpath('//div[@id="titleSection"]/h1[@id="title"]/span[@id="productTitle"]/text()'))
            url = "https://www.amazon.com" + check(
                html.xpath('//div[@class="a-section a-spacing-none"]/a[@id="bylineInfo"]/@href'))
            return title, url
